<template>
  <section class="user-center" v-loading="loading">
    <!-- 头部 -->
    <UserHeader
      ref="UserHeader"
      :userId="userId"
      :user="user"
      :userInfo="userInfo" 
      @getUserInfo="getUserInfo" 
      :showButton="showButton">
    </UserHeader>

    <div class="user-view">
      <UserLeft 
        class="user-view-left"  
        :user="user"
        :userId="userId"
        :userInfo="userInfo"
        @update="getUserInfo">
      </UserLeft>
 
      <div class="user-view-right">
        <el-tabs v-model="activeTab">
          <template v-for="tabItem in tabData">
            <el-tab-pane
              v-if="tabItem.isShow"
              :key="tabItem.name"
              :label="tabItem.label"
              :name="tabItem.name"
              lazy>
              <conponents 
                :is="tabItem.componentsName"
                :user="user"
                :userId="userId"
                :showButton="showButton"
                :class="tabItem.name"
                :style="{padding:tabItem.name === 'schedule' ? '0' : '17px'}"
                :is-me="isMe"
                mode="USER"
              >
              </conponents>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>
     
    </div>
  </section>
</template>

<script>
import {TenantType} from '@src/util/platform'
import platform from '@src/platform';
// tab展示数据
import tabData from './modal/tabData';

// 页面头部内容
import UserHeader from './components/UserHeader';
// 页面左边内容
import UserLeft from './components/UserLeft';

// tab-pane组件
// 基本信息
import tabPaneBaceMessage from './components/tabpane/tabPaneBaceMessage';
// 资质管理
import tabQualification from './components/tabpane/tabQualification';

// 会话
import tabPaneSession from './components/tabpane/tabPaneSession';
// 通话
import tabPaneCall from './components/tabpane/tabPaneCall';
// 事件
import tabPaneEvent from './components/tabpane/tabPaneEvent';
// 工单
import tabPaneWorkOrder from './components/tabpane/tabPaneWorkOrder';
// 客户
import tabPaneCustomer from './components/tabpane/tabPaneCustomer';
// 个人备件库
import tabPaneSpareParts from './components/tabpane/tabPaneSpareParts';
// 日程
import tabPaneSchedule from './components/tabpane/tabPaneSchedule';
    
import { getRootWindow } from '@src/util/dom';

/* enum */
import { TaskEventNameMappingEnum } from '@model/enum/EventNameMappingEnum.ts';
import StorageKeyEnum from '@model/enum/StorageKeyEnum'
/* mixin */
import { 
  VersionControlCalendarMixin,
  VersionControlTaskMixin,
  VersionControlSparePartMixin
} from '@src/mixins/versionControlMixin'
import { isNotUndefined } from '@src/util/type';

let win = getRootWindow(window);
let origin = window.location.origin;
export default {
  mixins: [
    VersionControlCalendarMixin,
    VersionControlTaskMixin,
    VersionControlSparePartMixin
  ],
  computed: {
    // 用户userId
    userId() {
      const pathname = window.location.pathname;
      if(pathname.indexOf('/mine/') > -1) return pathname.split('/mine/')[1];
      return pathname.split('/security/user/view/')[1];
    },
    isMe(){
      return this.loginUserId === this.userId
    }
  },
	watch: {
		activeTab(val) {
			const current = this.tabData.filter(item => item.name === val);
			this.$track.clickStat(this.$track.formatParams('USER_DETAIL_TABS', current[0].label))
		}
	},
  // provide: {
  //   // 为了控制台不报错
  //   initData: Object.freeze({})
  // },
   provide(){
    return{
      initData:{
        tenantType:TenantType
      }
    }
  },
  data() {
    return {
      loading:false,

      // 当前选中的tab名
      activeTab: 'baseMessage',
      // 接口返回的所有数据
      userInfo: {},
      // 和用户相关的数据，取自userInfo.user
      user: {},

      // 按钮权限
      showButton: {},

      // 右下角tab数据
      tabData,

      // 获取登陆的userId，匹配与当前页面的用户是否是同一个人
      loginUserId:localStorage.getItem('userId')
    }
  },

  components: {
    UserHeader,
    UserLeft,
    tabPaneBaceMessage,
    tabQualification,
    tabPaneSession,
    tabPaneCall,
    tabPaneEvent,
    tabPaneWorkOrder,
    tabPaneCustomer,
    tabPaneSpareParts,
    tabPaneSchedule,
  
  },

  mounted () {

    this.getUserInfo('mounted').then(()=>{
      this.initShowModifyChangePassWordDialog()
    });
    
    const frameElement = window.frameElement
    if (frameElement) {
      const currentTabId = frameElement.dataset.id;
      // TODO 国际化 标题是否需要修改
      // platform.setTabTitle({
      //   id: currentTabId,
      //   title:'用户详情'
      // })
    }
  },

  methods: {
    async getUserInfo(type){

      this.loading = true;

      try{ 
        const { status, message, data } = await this.$http.get(`/security/user/getDetail/${this.userId}`);
        this.loading = false;
        
        if(status != 0) return;

        this.userInfo = data || {};
        
        let { certificateList = []} = data.user

        // 解决下载时组件取的是id字段，但是接口返回的id不是fileId的问题
        certificateList.map(item=>{
          const { id, fileId } = item;
          fileId  && (item.id = fileId);
        })

        this.user = { ...data.user, certificateList, userFaceState:data?.userFaceState || false};
       
        
        this.showButton = data.showButton || {}; 

        this.loading = false;

        // 是否可以查看会话       isShowConversation
        // 是否可以查看通话       isShowCell
        // 是否可以查看事件      isShowCaseView
        // 是否可以查看工单      isShowTask
        // 是否可以查看客户      isShowCustomer
        // 是否显示个人备件库    isShowSparepart
        // 是否可以查看日程      isShowCalendar
        // 设置tab权限
        this.tabData.map((item,index) =>{
          if(item.permissionKey){
            let isShow = this.showButton[item.permissionKey] || false
            // 纯客服云版本隐藏工单、个人备件库、日程
            const judgePermissionArr = ['isShowTask', 'isShowSparepart', 'isShowCalendar']
            
            const keyByVersionShowMap = {
              isShowTask: this._isShowTaskModule,
              isShowSparepart: this._isShowSparePartPerson,
              isShowCalendar: this._isShowCalendarModule
            }
            
            if (judgePermissionArr.includes(item.permissionKey)) {
              const show = keyByVersionShowMap[item.permissionKey]
              isShow = isNotUndefined(show) ? show : isShow
            }
            
            item.isShow = isShow
          }
        })
        // 当前登陆的用户与当前页面是同一个人，需要更新右上角的用户信息
        if(this.loginUserId === this.userId){
            win.postMessage({ displayName:this.user.displayName }, origin);
        }

        // 更新日志,子组件触发
        type !== 'mounted' && (this.$eventBus.$emit(TaskEventNameMappingEnum.UpdateRecord));
        
      } catch(error){ 
        this.loading = false;
        console.log(error)
      } 
    },
    initShowModifyChangePassWordDialog() {
      try {
        
        // 是否显示修改密码弹窗
        const isShowModifyChangePassWordDialog = sessionStorage.getItem(StorageKeyEnum.PersonalCenterModifyPassword);
        if (!isShowModifyChangePassWordDialog) {
          return
        }
        
        // 清除 sessionStorage, 下次不再弹窗
        sessionStorage.removeItem(StorageKeyEnum.PersonalCenterModifyPassword);
        
        // 打开修改密码弹窗
        this.$refs.UserHeader.updatePwdBtnHandle()
        
      } catch (error) {
        console.error(error)
      }
    }
  },
}
</script>

<style lang="scss" scoped>
@import './common.scss';
section.user-center{
  padding:16px;
  width:100%;
  min-width:1200px;
  height:100%;
  position: relative;
  ::v-deep .el-dialog__headerbtn{
    top: 0;
  }
}

.user-view {
  display: flex;
  position: absolute;
  bottom: 16px;
  top: 116px;
  right: 16px;
  left: 16px;
  
  
  .user-view-left {
    width:400px;
    min-width:400px;
    background:#fff;
    border-radius: 4px;
    height:100%;
    overflow-y: hidden;
    .user-info {
      background: #fff;
      img {
        width: 60px;
        height: 60px;
        border-radius: 50%;
      }
      .info {
        display: flex;
        padding: 12px 12px 0 12px;
        .username {
          flex: 1;
          margin-left: 8px;
        }
        button {
          width: 80px;
          height: 36px;
          padding: 8px 10px;
          border-radius: 4px;
        }
      }
    }

  }
  .user-view-right {
    min-width:800px;
    height: 100%;
    overflow-y: auto; 
    background: #fff;
    margin-left: 12px;
    border-radius: 4px;
    flex:1;
    .el-tab-pane{
      height:100%;
    }
  }
}
</style>